/*
 * Copyright (c) 2012 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.chinadrtv.batch.admin.controller.ozing;

import com.chinadrtv.user.model.*;
import com.chinadrtv.user.service.UserManager;
import com.chinadrtv.user.service.ozing.OzingService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Jack.Chen
 * Date: 12-12-10
 */
@Controller
public class OzingUserCardMgrController {
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    private UserManager userManager = null;

    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    @Autowired
    private OzingService ozingService;

    public void setOzingService(OzingService ozingService) {
        this.ozingService = ozingService;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    @RequestMapping(value = "/ozing/user/cards/json", method = RequestMethod.GET)
    public String getUsers(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(required = false, defaultValue = "0") String start_index, @RequestParam(required = false, defaultValue = "30") String num_per_page,
                           @RequestParam(required = false) String cardType, @RequestParam(required = false) String cardId,
                           @RequestParam(required = false) String cardPassword, @RequestParam(required = false) String startDate,
                           @RequestParam(required = false) String endDate) throws IOException, JSONException, ParseException {

        Map searchParams = new HashMap<String, String>();
        searchParams.put("cardType", cardType);
        if (cardId != null && !cardId.trim().equals("")) searchParams.put("cardId", cardId);
        if (cardPassword != null && !cardPassword.trim().equals("")) searchParams.put("cardPassword", cardPassword);
        Date startDate_ = null;
        Date endDate_ = null;
        if (startDate != null && !startDate.trim().equals("")) startDate_ = sf.parse(startDate);
        if (startDate != null && !startDate.trim().equals("")) endDate_ = sf.parse(endDate);


        List<UserOzingCard> userOzingCards = ozingService.findPaginatedUserCards(Integer.valueOf(start_index), Integer.valueOf(num_per_page),
                searchParams, startDate == null ? null : startDate_, endDate == null ? null : endDate_);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        for (UserOzingCard userOzingCard : userOzingCards) {
            jsonObject = userOzingCard.to_json();
            jsonArray.put(jsonObject);
        }

        int totalRecords = ozingService.getUserCardsCount(searchParams, startDate == null ? null : startDate_, endDate == null ? null : endDate_);

        response.setContentType("text/json; charset=UTF-8");
        response.getWriter().write("{\"records\":" + jsonArray.toString() + ",\"totalRecords\":" + totalRecords + ",\"startIndex\":" + start_index + " }");
        return null;
    }

    @RequestMapping(value = "/ozing/user/cards/his/json", method = RequestMethod.GET,  produces  = "application/json")
    public String handleUserOzingCardHisXmlRequest(@RequestParam(required = false, defaultValue = "0") int start_index,
                                                   @RequestParam Integer num_per_page,
                                                   @RequestParam(required = false) String sort,
                                                   @RequestParam(required = false) String dir,
                                                   @RequestParam(required = false) String username, @RequestParam(required = false) String access_token, String cardId,
                                                   HttpServletResponse response) throws IOException, JSONException {
        List<UserOzingCardTx> ozingCardTxList = ozingService.findOzingCardHisByUsernameAndCardId(username, cardId, true,start_index, num_per_page, sort, dir);
        JSONArray usersJsonArray = new JSONArray();
        for (UserOzingCardTx tx_ : ozingCardTxList) {
            usersJsonArray.put(tx_.to_json_full());
        }
        int totalRecords = ozingService.findOzingCardHisCount(username, cardId, true);
        response.setContentType("text/json");
        response.getWriter().print("{\"records\":" + usersJsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index + ",\"sort\":\"" + sort + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }


    @RequestMapping(value = "/ozing/users/cards/his", method = RequestMethod.GET)
    public String userCard() {
        return "ozing/users_cards_his";
    }

    @RequestMapping(value = "/ozing/users/cards", method = RequestMethod.GET)
    public String refundCard() {
        return "ozing/users_cards";
    }

    @RequestMapping(value = "/admin/ozing/user/cards", method = RequestMethod.GET)
    public ModelAndView getUsers(@RequestParam Long id, HttpServletRequest request, HttpServletResponse response){
        User user = userManager.getUserDetail(id);
        UserOzingBalance balance = ozingService.findOzingCardPointsByUsername(user.getUsername());
        List<DeviceOzingGiftCardHis> giftCardHisList = ozingService.findDeviceOzingGiftCardHis(user.getUsername());
        Map<String, Object> objectMap = new HashMap<String, Object>();
        objectMap.put("user", user);
        objectMap.put("totalBalance", balance.getCardTotalBalance());
        objectMap.put("validBalance", balance.getCardBalance());
        objectMap.put("lockedBalance", balance.getCardLockedBalance());
        objectMap.put("cardGiftHis", giftCardHisList);

        return new ModelAndView("ozing/user_cards", objectMap);
    }

    @RequestMapping(value = "/admin/ozing/gift/reset", method = RequestMethod.GET)
    public @ResponseBody Object resetGiftCardHis(@RequestParam String username, HttpServletRequest request, HttpServletResponse response){
        ozingService.resetGiftCardHis(username);
        return true;
    }

    @RequestMapping(value = "/admin/ozing/user/gift/card", method = RequestMethod.POST)
    public  @ResponseBody Object addGiftCardToUser(@RequestParam String username, @RequestParam Long gift_card_par_value, @RequestParam Date cardExpirationDate, HttpServletRequest request, HttpServletResponse response){
    	UserOzingBalance balance = ozingService.findOzingCardPointsByUsername(username);
    	
        return ozingService.addGiftOzingCardToUser(username, gift_card_par_value, cardExpirationDate, balance);
    }

}
